package com.example.test_flutter_message_channel

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.annotations.SerializedName
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.*
import java.io.InputStream
import java.nio.ByteBuffer
import kotlin.math.log

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        // 0.1k
        var contactModel100 = ContactModel()
        // 1k
        var contactModel1000 = ContactModel()

        for (i in 1..3) {
            contactModel100.add(ContactDetails("name", "phone"));
        }

        for (i in 1..32) {
            contactModel1000.add(ContactDetails("name", "phone"));
        }

        MethodChannel(flutterEngine.dartExecutor, "methodChannelDemo")
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "setContacts100" -> {
                        val contacts: String? = call.argument<String>("contacts");
                        // println(contacts!!.length.toString());
                        contactModel100.fromJson(contacts!!);
                        result.success(1);
                    }
                    "setContacts1000" -> {
                        val contacts: String? = call.argument<String>("contacts");
                        // println(contacts.length); // 1025
                        contactModel1000.fromJson(contacts!!);
                        result.success(1);
                    }
                    else -> result.notImplemented()
                }
            }

        BasicMessageChannel(flutterEngine.dartExecutor, "jsonMessageCodecDemo", JSONMessageCodec.INSTANCE)
            .setMessageHandler { message, reply ->
                if (message == "getContact100") {
                    reply.reply(contactModel100.toJson())
                } else if (message == "getContact1000") {
                    reply.reply(contactModel1000.toJson())
                } else {
                    reply.reply(null)
                }
            }
    }
}

open class ContactDetails(@SerializedName("name") open var name: String, @SerializedName("phone") open var phone: String) {}

open class ContactModel {
    open var contacts: MutableCollection<ContactDetails> = mutableListOf();

    private val gson = Gson();

    open fun add(contact: ContactDetails) {
        contacts.add(contact);
    }

    fun fromJson(jsonString: String) {
        contacts = gson.fromJson(jsonString, object : TypeToken<MutableCollection<ContactDetails>>() {}.type);
    }

    fun toJson() : String {
        return gson.toJson(mapOf("contacts" to contacts));
    }
}
